package com.itplh.java8.optional;

import java.util.Optional;

/**
 * @author: tanpeng
 * @date: 2019-06-17 10:00
 * @desc:
 */
public class ApiTest {
    public static void main(String[] args) {
        System.out.println("******************null******************");
        String nullStr = null;
        testOptionalApi(nullStr);
        System.out.println("******************not null******************");
        String str = "Hello World";
        testOptionalApi(str);
    }

    private static void testOptionalApi(String inputSource) {
        if (!Optional.ofNullable(inputSource).isPresent()) {
            System.out.println("inputSource is null");
            return;
        }
        Optional.empty().ifPresent(System.out::println);
        System.out.println("------------------empty----------------");
        // inputSource == null; NullPointerException
        Optional.of(inputSource).ifPresent(System.out::println);
        System.out.println("------------------of----------------");
        Optional<String> ofNullable = Optional.ofNullable(inputSource);
        ofNullable.ifPresent(System.out::println);
        System.out.println("------------------ofNullable----------------");

        // inputSource == null; NoSuchElementException: No value present
        System.out.println(ofNullable.get());
        System.out.println("------------------get----------------");
        System.out.println(ofNullable.orElse("value is null"));
        System.out.println("------------------orElse----------------");
        System.out.println(ofNullable.orElseGet(() -> new String("value is null")));
        System.out.println("------------------orElseGet----------------");

        System.out.println(ofNullable.isPresent());
        System.out.println("------------------isPresent----------------");
        ofNullable.ifPresent(System.out::println);
        System.out.println("------------------ifPresent----------------");

        ofNullable.map(str -> str.concat(" Hello Optional")).ifPresent(System.out::println);
        System.out.println("------------------map----------------");
        Optional.ofNullable(inputSource).flatMap(str -> Optional.ofNullable(str.substring(3))).ifPresent(System.out::println);
        System.out.println("------------------flatMap 扁平化 --> 和map做对比，map要求返回值和调用map的对象保持一致；flatMap可以改变返回值的类型----------------");
        ofNullable.filter(str -> str.length() > 10).ifPresent(System.out::println);
        System.out.println("------------------filter----------------");

        System.out.println();
    }

}
